<?php
/***************************************************************
*  Copyright notice
*
*  (c) 2008 Starbugs <univis2typo3@googlegroups.com>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/

require_once(PATH_tslib.'class.tslib_pibase.php');
require_once (t3lib_extMgm::extPath('xajax') . 'class.tx_xajax.php');

/**
 * Plugin 'persons' for the 'univis2typo3' extension.
 *
 * @author	Starbugs <univis2typo3@googlegroups.com>
 * @package	TYPO3
 * @subpackage	tx_univis2typo3
 */
class tx_univis2typo3_pi1 extends tslib_pibase {
	// Same as class name
	var $prefixId      = 'tx_univis2typo3_pi1';
	// Path to this script relative to the extension dir
	var $scriptRelPath = 'pi1/class.tx_univis2typo3_pi1.php';
	// The extension key
	var $extKey        = 'univis2typo3';

	var $pi_checkCHash = true;

	var $department = "";

	var $emailDivIdPrefixi_ = 'u2t3_';

	var $language = 0;

	var $postfix = '_EN';

	/**
	 * The main method of the PlugIn
	 *
	 * @param	string		$content: The PlugIn content
	 * @param	array		$conf: The PlugIn configuration
	 * @return	The content that is displayed on the website
	 */
	function main($content, $conf)	{
		$this->conf = $conf;
		$this->pi_setPiVarDefaults();
		$this->pi_loadLL();

		$this->language = $GLOBALS["TSFE"]->sys_language_uid;

		$this->department = $this->conf['department_id'];
// AJAX Stuff...
		// Make an instance of class tx_xajax
		$this->xajax = t3lib_div::makeInstance('tx_xajax');
		$this->xajax->decodeUTF8InputOn();
		// Encode of the response to utf-8 ???
 		//$this->xajax->setCharEncoding("iso-8859-1");
 		$this->xajax->setCharEncoding("utf-8");
		// To prevent conflicts, prepend the extension prefix
		$this->xajax->setWrapperPrefix($this->prefixId);

		$this->xajax->debugOff();
//  		$this->xajax->debugOn();

		// $xajax->registerFunction(array('functionNameInJavascript', &$object, 'methodName'));
		$this->xajax->registerFunction(array('changeMail', &$this, 'changeMail'));

		// If this is an xajax request, call our registered function, send output and exit
		$this->xajax->processRequests();
		// Else create javascript and add it to the header output
		$GLOBALS['TSFE']->additionalHeaderData[$this->prefixId] = $this->xajax->getJavascript(t3lib_extMgm::siteRelPath('xajax'));
// /AJAX Stuff


		$templateCode = $this->cObj->fileResource($this->conf['templateFile']);
		
		// Flex-Form initialisieren
		$this->pi_initPIflexForm();

		$this->postfix = (1 == $this->language) ? '_DE' : '_EN';
		
		if( $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'what_to_display', 'sDEF') == 16)
			$this->template = $this->cObj->getSubpart($templateCode,"###TEMPLATE_ALUMNI###");
		else
			$this->template = $this->cObj->getSubpart($templateCode,"###TEMPLATE_PERSON".$this->postfix."###");
		
		$content = $this->getContent($this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'what_to_display', 'sDEF'));
		return $this->pi_wrapInBaseClass($content);
	}

	function getHead($groupId) {
		$select 	= '`txp`.`firstname`, `txp`.`lastname`, `loc`.`url`';
		$from		= "`tx_u2t3_job`"
				    . " LEFT JOIN `u_person_jobs` AS `upj` ON `upj`.`job_key` = CONCAT('Leitung ', `tx_u2t3_job`.`description`)"
				    . " LEFT JOIN `tx_u2t3_person` AS `txp` ON `txp`.`key` = `upj`.`per`"
					. " LEFT JOIN `u_person_location` as `loc` on `loc`.`person_key` = `upj`.`per`";
		$where		= "`tx_u2t3_job`.`uid` = {$groupId} AND txp.department_id =".$this->department;
		$groupby	= '';
		$orderby	= '';
		$limit 		= '1';

		$query = $GLOBALS['TYPO3_DB']->SELECTquery(
			$select,
			$from,
			$where,
			$groupby,
			$orderby,
			$limit
		);
		$res = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
		if (mysql_num_rows($res) == 0) 
				return null;

		return $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
	}

	function getItems($group) {
		$select 	= ' T1.per as per, T1.job_key as job_key,
				    T2.uid as per_uid, T2.key as per_key, T2.type as per_type, T2.group as per_group, T2.atitle as per_title, T2.firstname as firstname, T2.lastname as lastname, T2.id as per_id,
				    T2.title as title, T2.visible as visible,
				    T3.uid as job_uid, T3.parent_key as job_parent_key, T3.description as job_description, T3.description_en as job_description_en,
				    T4.email as per_email, T4.tel as per_tel, T4.office as per_office, T4.url as per_url, T5.job_url, T5.job_url_en';
		$from		= ' u_person_jobs as T1 
				    JOIN tx_u2t3_person as T2 ON T1.per = T2.key 
				    JOIN tx_u2t3_job as T3 ON T3.description = T1.job_key 
				    JOIN u_person_location as T4 ON T4.person_key = T2.key
					LEFT OUTER JOIN tx_u2t3_research_group as T5 ON T1.job_key = T5.description'; 
		$where		= "T3.uid =" . $group;
		$groupby	= '';
		$orderby	= 'T2.lastname, T2.firstname';
		$limit 		= '';
		$query = $GLOBALS['TYPO3_DB']->SELECTquery(
			$select,
			$from,
			$where,
			$groupby,
			$orderby,
			$limit
		);
		//echo '<!-- ' . $query . ' -->';
		return $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
	}

	function getContent($group) {
		$items = $this->getItems($group);
		
		// check if there are some results otherwise skip this group
		if (0 == mysql_num_rows($items))
			return '';
		
		$arrMarker = array();
		$arrWrappedPersonSubpart = array();
		$row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($items); // get first row
		$GLOBALS['TYPO3_DB']->sql_data_seek($items, 0); // reset internal pointer ==> only peek

		$jobname = (1 == $this->language) ? 'job_description' : 'job_description_en';
		$url = (1 == $this->language) ? 'job_url' : 'job_url_en';

		$arrWrappedPersonSubpart['###TMPL_P_GRP_LNK_OPEN###'] = '';
		$arrWrappedPersonSubpart['###TMPL_P_GRP_LNK_CLOSE###'] = '';
		if ('' != $row[$url]) {
		    $arrWrappedPersonSubpart['###TMPL_P_GRP_LNK_OPEN###'] = "<a class='p-grp-link' href='{$row[$url]}'>";
		    $arrWrappedPersonSubpart['###TMPL_P_GRP_LNK_CLOSE###'] = '</a>';
		}
		$arrWrappedPersonSubpart['###TMPL_P_GRP_DESC###'] = $row[$jobname];
		$arrWrappedPersonSubpart['###TEMPLATE_PERSON_HEAD_ITEM###'] = '';
		
		$head = $this->getHead($group);

		if (null != $head) {
			$localHead = (1 == $this->language) ? '(Leitung: ' : '(Head: ';

			$headName = $head['firstname'] . ' ' . $head['lastname'];

			/*if ('' != $head['url'])
				$headName = "<a href='{$head['url']}'>" . $headName . "</a>";*/

			$arrWrappedPersonSubpart['###TEMPLATE_PERSON_HEAD_ITEM###'] = $localHead.$headName.')';
		}

		$hints = array('Haber' => 'Haberstra&szlig;e 2',
				'NukMed' => 'Krankenhausstr. 12',
			      );

		$content = '';
		$temp_i = 0;
		while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($items)) {
			$arrMarker['###P_IDX###'] = ''.(int)$i;
			$arrMarker['###P_U_KEY###'] = $row['per_key'];
			$arrMarker['###P_FIRSTNAME###'] = $row['firstname'];
			$arrMarker['###P_LASTNAME###'] = $row['lastname'];
			
			$arrMarker['###P_URL_OPEN###']  = "";
			$arrMarker['###P_URL_CLOSE###'] = "";
			if($row['per_url'] != "") 
			{
				$arrMarker['###P_URL_OPEN###'] = "<a href='".$row['per_url']."'>";
				$arrMarker['###P_URL_CLOSE###']  = "</a>";
			}
			$arrMarker['###P_PHONE###'] = $row['per_tel'];
			$arrMarker['###P_EMAIL_CODE###'] = $this->ajaxEmailHtmlCode('u2t3_'.$row['person_key'].'-'.(int)$i);

			$office_html = $row['per_office'];
			if ($office_html) {
				$office = $office_html;
				$hint  = false;

				list($floor,$room) = explode('.', $office);
				if ('02' == $floor) { $hint = 'NukMed'; } // Klinik
				if ( '1' == $floor) { $hint = 'Haber';  } // Haberstr

				if ($hint) {
					$office_html .= ' (';
					if ($hints[$hint]) {
						$office_html .= '<a href="javascript:alert(\'Der Raum '.$office . ' befindet sich in der ' . $hints[$hint].'.\');">';
					}
					$office_html .= $hint;
					if ($hints[$hint]) {
						$office_html .= '</a>';
					}
					$office_html .= ')';
				} else { 
					if (file_exists('images/maps/'.$office.'.gif')) {
						$office_html = '<a href="/images/maps/' . $office . '.gif" rel="lightbox['.$group.'-'.$temp_i++.']">'
								. $office
								. '</a>';
					} else {
						// empty
					}
				}
			}
			$arrMarker['###P_OFFICE###'] = $office_html;

			/* HH: see above.
			// if image exists, link image
			if (($row['per_office'] != '') && file_exists('images/maps/'.$row['per_office'].'.gif'))
			{
				$arrMarker['###P_OFFICE###'] = '<a href="images/maps/'.$row['per_office'].'.gif" rel="lightbox['.$group.'-'.$temp_i++.']">'.$row['per_office'].'</a>';
			} else {
				// otherwise no link information
				$arrMarker['###P_OFFICE###'] = $row['per_office'];
			}
			*/
			/* HH: moved HTML code into the template, where it belongs */
			$content .= $this->cObj->substituteMarkerArrayCached(
			    $this->cObj->getSubpart($this->template,"###TEMPLATE_PERSON_ITEM###"),
			    $arrMarker);
		}

		$arrWrappedPersonSubpart['###TEMPLATE_PERSON_ITEM###'] = $content;
		return $this->cObj->substituteMarkerArrayCached(
					$this->template,
					$arrMarker,
					$arrWrappedPersonSubpart);
	}

	function ajaxEmailHtmlCode($data, $email = null) {
	    if (is_null($email)) {
		return '<span class="email">'
			. ((0 == $this->language) ? 'show email' : 'E-Mail anzeigen')
			. '</span>';
	    } else {
		// Niemann Hack
		if ('niemann' == substr($email, 0, 7)) {
		    return '<span class="email">'
			    . ((0 == $this->language) ? 'This email is protected.' : 'Diese E-Mail wird nicht angezeigt.')
			    . '</span>';
		}
		return "<a href='mailto:{$email}' class='email'>{$email}</a>";
	    }
	}

	function changeMail($data, $ref) {

		if(1 == $ref) 
		{
			$persKey = '';
			$prefixLen = strlen($this->emailDivIdPrefixi_);
			$pos = strpos($data, '-');
			if ($pos !== false) 
			{
				$persKey = substr($data, $prefixLen, $pos - $prefixLen);
			} else {
				$persKey = substr($data, $prefixLen);
			}

			$select		= '*';
			$from		= 'tx_u2t3_person JOIN u_person_location ON u_person_location.person_key = tx_u2t3_person.`key`';
			$where		= "tx_u2t3_person.`key` = '" . $persKey . "'";
			$groupby	= '';
			$orderby	= '';
			$limit 		= '';

			$query = $GLOBALS['TYPO3_DB']->SELECTquery(
			    $select,
			    $from,
			    $where,
			    $groupby,
			    $orderby,
			    $limit
			);

			$res = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
			$row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);

			$content = $this->ajaxEmailHtmlCode($data, $row['email']);
	    } else {
			$content = $this->ajaxEmailHtmlCode($data);
	    }

	    $objResponse = new tx_xajax_response();
	    $objResponse->setCharEncoding("iso-8859-1");
	    $objResponse->addAssign($data, 'innerHTML', $content);
	    return $objResponse->getXML();
	}
}

if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/univis2typo3/pi1/class.tx_univis2typo3_pi1.php']) {
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/univis2typo3/pi1/class.tx_univis2typo3_pi1.php']);
}

?>
